package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/08/30 09:14
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    /*@Autowired
    PlatformTransactionManager transactionManager;*/

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(int fromId, int destId, int money) {
        /**/
        //提供TransactionCallBack的实例，doInTransaction方法里应该写需要增加事务的业务代码
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                int fromMoney = accountMapper.selectById(fromId);
                int destMoney = accountMapper.selectById(destId);

                fromMoney -= money; // 转出方money减少
                destMoney += money; // 接收方money变多

                accountMapper.updateById(fromMoney, fromId);
                int i = 1 / 0;
                accountMapper.updateById(destMoney, destId);
                return null;
            }
        });
    }
}
